<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>如何避免反射和序列化破坏单例模式 | Reality</title><meta name="keywords" content="设计模式"><meta name="author" content="dtyy"><meta name="copyright" content="dtyy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="单例模式的研究重点有以下几个：  构造私有，提供静态输出接口 线程安全，确保全局唯一 延迟初始化 防止反射攻击 防止序列化破坏单例模式  上一节《单例设计模式实现总结》，我们使用饿汉式、双重锁检查、静态内部类、枚举类实践了前3条。然而光并发安全并不能保证唯一实例，反射和序列化可以破坏单例模式。 public class ReflectSingleton {     private final st">
<meta property="og:type" content="article">
<meta property="og:title" content="如何避免反射和序列化破坏单例模式">
<meta property="og:url" content="https://dtyytop.gitee.io/2021/05/21/devnotes/zhi-mian-java/she-ji-mo-shi/ru-he-bi-mian-fan-she-he-xu-lie-hua-po-pi-dan-li-mo-shi/index.html">
<meta property="og:site_name" content="Reality">
<meta property="og:description" content="单例模式的研究重点有以下几个：  构造私有，提供静态输出接口 线程安全，确保全局唯一 延迟初始化 防止反射攻击 防止序列化破坏单例模式  上一节《单例设计模式实现总结》，我们使用饿汉式、双重锁检查、静态内部类、枚举类实践了前3条。然而光并发安全并不能保证唯一实例，反射和序列化可以破坏单例模式。 public class ReflectSingleton {     private final st">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg">
<meta property="article:published_time" content="2021-05-21T15:28:04.000Z">
<meta property="article:modified_time" content="2021-05-22T12:45:04.784Z">
<meta property="article:author" content="dtyy">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://dtyytop.gitee.io/2021/05/21/devnotes/zhi-mian-java/she-ji-mo-shi/ru-he-bi-mian-fan-she-he-xu-lie-hua-po-pi-dan-li-mo-shi/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"prismjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: true
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: dtyy","link":"链接: ","source":"来源: Reality","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '如何避免反射和序列化破坏单例模式',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-05-22 20:45:04'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Reality" type="application/atom+xml">

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Reality</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">如何避免反射和序列化破坏单例模式</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-05-21T15:28:04.000Z" title="发表于 2021-05-21 23:28:04">2021-05-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-05-22T12:45:04.784Z" title="更新于 2021-05-22 20:45:04">2021-05-22</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>4分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="如何避免反射和序列化破坏单例模式"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>单例模式的研究重点有以下几个：</p>
<ol>
<li>构造私有，提供静态输出接口</li>
<li>线程安全，确保全局唯一</li>
<li>延迟初始化</li>
<li><strong>防止反射攻击</strong></li>
<li><strong>防止序列化破坏单例模式</strong></li>
</ol>
<p>上一节《单例设计模式实现总结》，我们使用饿汉式、双重锁检查、静态内部类、枚举类实践了前3条。然而光并发安全并不能保证唯一实例，反射和序列化可以破坏单例模式。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ReflectSingleton</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token class-name">ReflectSingleton</span> instance <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ReflectSingleton</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token class-name">ReflectSingleton</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">ReflectSingleton</span> <span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> instance<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>本文中采用饿汉单例模式作为最初代码，演示如何避免反射和序列化破坏单例模式。</p>
<h2 id="防止反射攻击"><a href="#防止反射攻击" class="headerlink" title="防止反射攻击"></a>防止反射攻击</h2><h3 id="使用反射攻击单例模式"><a href="#使用反射攻击单例模式" class="headerlink" title="使用反射攻击单例模式"></a>使用反射攻击单例模式</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Client</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">{</span>
        <span class="token comment">// 通过全局访问方法创建实例</span>
        <span class="token class-name">ReflectSingleton</span> instance <span class="token operator">=</span> <span class="token class-name">ReflectSingleton</span><span class="token punctuation">.</span><span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 通过反射创建实例</span>
        <span class="token class-name">Constructor</span> constructor <span class="token operator">=</span> <span class="token class-name">ReflectSingleton</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getDeclaredConstructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        constructor<span class="token punctuation">.</span><span class="token function">setAccessible</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">ReflectSingleton</span> newInstance <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">ReflectSingleton</span><span class="token punctuation">)</span> constructor<span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>instance<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>newInstance<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>instance <span class="token operator">==</span> newInstance<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>使用反射时，需要添加构造器权限，否则会抛异常。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Exception</span> in thread <span class="token string">"main"</span> <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>IllegalAccessException</span><span class="token operator">:</span> <span class="token class-name">Class</span> <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>lzp<span class="token punctuation">.</span>java<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>singleton<span class="token punctuation">.</span>destroysingleton<span class="token punctuation">.</span></span>Client</span> can not access a member of <span class="token keyword">class</span> <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>lzp<span class="token punctuation">.</span>java<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>singleton<span class="token punctuation">.</span>destroysingleton<span class="token punctuation">.</span></span>ReflectSingleton</span> <span class="token keyword">with</span> <span class="token namespace">modifiers</span> <span class="token string">"private"</span>
	at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span>Reflection</span><span class="token punctuation">.</span><span class="token function">ensureMemberAccess</span><span class="token punctuation">(</span><span class="token class-name">Reflection</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">102</span><span class="token punctuation">)</span>
	at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span>AccessibleObject</span><span class="token punctuation">.</span><span class="token function">slowCheckMemberAccess</span><span class="token punctuation">(</span><span class="token class-name">AccessibleObject</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">296</span><span class="token punctuation">)</span>
	at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span>AccessibleObject</span><span class="token punctuation">.</span><span class="token function">checkAccess</span><span class="token punctuation">(</span><span class="token class-name">AccessibleObject</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">288</span><span class="token punctuation">)</span>
	at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span>Constructor</span><span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token class-name">Constructor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">413</span><span class="token punctuation">)</span>
	at <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>lzp<span class="token punctuation">.</span>java<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>singleton<span class="token punctuation">.</span>destroysingleton<span class="token punctuation">.</span></span>Client</span><span class="token punctuation">.</span><span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">Client</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">16</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>运行结果：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>lzp<span class="token punctuation">.</span>java<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>singleton<span class="token punctuation">.</span>destroysingleton<span class="token punctuation">.</span></span>ReflectSingleton</span><span class="token annotation punctuation">@355da254</span>
<span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>lzp<span class="token punctuation">.</span>java<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>singleton<span class="token punctuation">.</span>destroysingleton<span class="token punctuation">.</span></span>ReflectSingleton</span><span class="token annotation punctuation">@4dc63996</span>
<span class="token boolean">false</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h3 id="改进措施：反射防御"><a href="#改进措施：反射防御" class="headerlink" title="改进措施：反射防御"></a>改进措施：反射防御</h3><p>抵御这种攻击，可以在构造器中添加反射防御代码，让它在被要求创建第二个实例时抛出异常。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token class-name">ReflectSingleton</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>instance <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span><span class="token string">"禁止反射调用创建多个实例"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>运行结果：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Exception</span> in thread <span class="token string">"main"</span> <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span>InvocationTargetException</span>
	at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span>NativeConstructorAccessorImpl</span><span class="token punctuation">.</span><span class="token function">newInstance0</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
	at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span>NativeConstructorAccessorImpl</span><span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token class-name">NativeConstructorAccessorImpl</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">62</span><span class="token punctuation">)</span>
	at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span>DelegatingConstructorAccessorImpl</span><span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token class-name">DelegatingConstructorAccessorImpl</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">45</span><span class="token punctuation">)</span>
	at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span>Constructor</span><span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token class-name">Constructor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">423</span><span class="token punctuation">)</span>
	at <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>lzp<span class="token punctuation">.</span>java<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>singleton<span class="token punctuation">.</span>destroysingleton<span class="token punctuation">.</span></span>Client</span><span class="token punctuation">.</span><span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">Client</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">18</span><span class="token punctuation">)</span>
<span class="token class-name">Caused</span> by<span class="token operator">:</span> <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>RuntimeException</span><span class="token operator">:</span> 禁止反射调用创建多个实例<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>需要注意的是，在构造器中添加反射防御代码，仅适用于基于类初始化加载的单例实现，即饿汉式和静态内部类实现。对于双重锁检查不会出现反射攻击的情况。</p>
<h2 id="防止序列化破坏单例模式"><a href="#防止序列化破坏单例模式" class="headerlink" title="防止序列化破坏单例模式"></a>防止序列化破坏单例模式</h2><h3 id="反序列化问题"><a href="#反序列化问题" class="headerlink" title="反序列化问题"></a>反序列化问题</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Client2</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">{</span>
        <span class="token comment">// 使用全局访问方法创建实例</span>
        <span class="token class-name">SerializeSingleton</span> instance <span class="token operator">=</span> <span class="token class-name">SerializeSingleton</span><span class="token punctuation">.</span><span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// 写出对象到项目目录下singleton.txt文件</span>
        <span class="token class-name">ObjectOutputStream</span> oos <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ObjectOutputStream</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">FileOutputStream</span><span class="token punctuation">(</span><span class="token string">"singleton.txt"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        oos<span class="token punctuation">.</span><span class="token function">writeObject</span><span class="token punctuation">(</span>instance<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 读入对象</span>
        <span class="token class-name">ObjectInputStream</span> ois <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ObjectInputStream</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">FileInputStream</span><span class="token punctuation">(</span><span class="token string">"singleton.txt"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">SerializeSingleton</span> newInstance <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">SerializeSingleton</span><span class="token punctuation">)</span> ois<span class="token punctuation">.</span><span class="token function">readObject</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>instance<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>newInstance<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>instance <span class="token operator">==</span> newInstance<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>运行结果：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>lzp<span class="token punctuation">.</span>java<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>singleton<span class="token punctuation">.</span>destroysingleton<span class="token punctuation">.</span></span>SerializeSingleton</span><span class="token annotation punctuation">@4b1210ee</span>
<span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>lzp<span class="token punctuation">.</span>java<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>singleton<span class="token punctuation">.</span>destroysingleton<span class="token punctuation">.</span></span>SerializeSingleton</span><span class="token annotation punctuation">@27973e9b</span>
<span class="token boolean">false</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h3 id="改进措施：添加readResolve-方法"><a href="#改进措施：添加readResolve-方法" class="headerlink" title="改进措施：添加readResolve()方法"></a>改进措施：添加readResolve()方法</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token class-name">Object</span> <span class="token function">readResolve</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> instance<span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>运行结果：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>lzp<span class="token punctuation">.</span>java<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>singleton<span class="token punctuation">.</span>destroysingleton<span class="token punctuation">.</span></span>SerializeSingleton</span><span class="token annotation punctuation">@4b1210ee</span>
<span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>lzp<span class="token punctuation">.</span>java<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>singleton<span class="token punctuation">.</span>destroysingleton<span class="token punctuation">.</span></span>SerializeSingleton</span><span class="token annotation punctuation">@4b1210ee</span>
<span class="token boolean">true</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h3 id="为什么是readResolve-，而不是其他方法？"><a href="#为什么是readResolve-，而不是其他方法？" class="headerlink" title="为什么是readResolve()，而不是其他方法？"></a>为什么是readResolve()，而不是其他方法？</h3><p>此时可以对源码做单步调试。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 核心语句</span>
<span class="token class-name">SerializeSingleton</span> newInstance <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">SerializeSingleton</span><span class="token punctuation">)</span> ois<span class="token punctuation">.</span><span class="token function">readObject</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// ObjectInputStream</span>
<span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token class-name">Object</span> <span class="token function">readObject</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>
    <span class="token class-name">Object</span> obj <span class="token operator">=</span> <span class="token function">readObject0</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>readObject方法内部调用readObject0方法。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// ObjectInputStream</span>
<span class="token keyword">private</span> <span class="token class-name">Object</span> <span class="token function">readObject0</span><span class="token punctuation">(</span><span class="token keyword">boolean</span> unshared<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span> <span class="token punctuation">{</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>
        <span class="token keyword">switch</span> <span class="token punctuation">(</span>tc<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
            <span class="token keyword">case</span> TC_OBJECT<span class="token operator">:</span>  <span class="token comment">// 如果是读取对象Object</span>
                <span class="token keyword">return</span> <span class="token function">checkResolve</span><span class="token punctuation">(</span><span class="token function">readOrdinaryObject</span><span class="token punctuation">(</span>unshared<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
            <span class="token keyword">default</span><span class="token operator">:</span>
                <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">StreamCorruptedException</span><span class="token punctuation">(</span>
                    <span class="token class-name">String</span><span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span><span class="token string">"invalid type code: %02X"</span><span class="token punctuation">,</span> tc<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
        depth<span class="token operator">--</span><span class="token punctuation">;</span>
        bin<span class="token punctuation">.</span><span class="token function">setBlockDataMode</span><span class="token punctuation">(</span>oldMode<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>定位到关键方法readOrdinaryObject()。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// ObjectInputStream</span>
<span class="token keyword">private</span> <span class="token class-name">Object</span> <span class="token function">readOrdinaryObject</span><span class="token punctuation">(</span><span class="token keyword">boolean</span> unshared<span class="token punctuation">)</span>
    <span class="token keyword">throws</span> <span class="token class-name">IOException</span>
<span class="token punctuation">{</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    <span class="token class-name">Object</span> obj<span class="token punctuation">;</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>
        <span class="token comment">// 注：如果为true，通过反射创建新的实例</span>
        obj <span class="token operator">=</span> desc<span class="token punctuation">.</span><span class="token function">isInstantiable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">?</span> desc<span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> ex<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">throw</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span><span class="token punctuation">)</span> <span class="token keyword">new</span> <span class="token class-name">InvalidClassException</span><span class="token punctuation">(</span>
            desc<span class="token punctuation">.</span><span class="token function">forClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token string">"unable to create instance"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">initCause</span><span class="token punctuation">(</span>ex<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>obj <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span>
        handles<span class="token punctuation">.</span><span class="token function">lookupException</span><span class="token punctuation">(</span>passHandle<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span>
        desc<span class="token punctuation">.</span><span class="token function">hasReadResolveMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token comment">// 内部核心语句：return readResolveMethod.invoke(obj, (Object[]) null);</span>
        <span class="token comment">// 反射创建原实例</span>
        <span class="token class-name">Object</span> rep <span class="token operator">=</span> desc<span class="token punctuation">.</span><span class="token function">invokeReadResolve</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>unshared <span class="token operator">&amp;&amp;</span> rep<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            rep <span class="token operator">=</span> <span class="token function">cloneArray</span><span class="token punctuation">(</span>rep<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>rep <span class="token operator">!=</span> obj<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment">// 替换对象</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>rep <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>rep<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token function">filterCheck</span><span class="token punctuation">(</span>rep<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token class-name">Array</span><span class="token punctuation">.</span><span class="token function">getLength</span><span class="token punctuation">(</span>rep<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
                    <span class="token function">filterCheck</span><span class="token punctuation">(</span>rep<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
            handles<span class="token punctuation">.</span><span class="token function">setObject</span><span class="token punctuation">(</span>passHandle<span class="token punctuation">,</span> obj <span class="token operator">=</span> rep<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">return</span> obj<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment">/**
 * 如果类是可序列化的，返回true
 */</span>
<span class="token keyword">boolean</span> <span class="token function">isInstantiable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">requireInitialized</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token punctuation">(</span>cons <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment">/**
 * 如果类是可序列化的，并且定义了readResolve()方法，返回true；否则返回false
 */</span>
<span class="token keyword">boolean</span> <span class="token function">hasReadResolveMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">requireInitialized</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token punctuation">(</span>readResolveMethod <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>通过调试，我们可以看出，调readObject()方法反序列化的过程中，总会创建一个新的实例。如果SerializeSingleton类中定义了readResolve方法，就通过反射创建原实例，返回时覆盖之前创建的实例。否则，返回新的实例。</p>
<p>通过底层代码分析，我们便清楚了为什么用的是readResolve方法，而不是其他。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">dtyy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://dtyytop.gitee.io/2021/05/21/devnotes/zhi-mian-java/she-ji-mo-shi/ru-he-bi-mian-fan-she-he-xu-lie-hua-po-pi-dan-li-mo-shi/">https://dtyytop.gitee.io/2021/05/21/devnotes/zhi-mian-java/she-ji-mo-shi/ru-he-bi-mian-fan-she-he-xu-lie-hua-po-pi-dan-li-mo-shi/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://dtyytop.gitee.io" target="_blank">Reality</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/05/16/devnotes/xiao-bai-xue-qian-duan/xiao-ji-qiao/vscode-kuai-jie-pei-zhi/"><img class="prev-cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Vscode快捷配置</div></div></a></div><div class="next-post pull-right"><a href="/2021/05/21/devnotes/zhi-mian-java/she-ji-mo-shi/dan-li-she-ji-mo-shi-shi-xian-zong-jie/"><img class="next-cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222600.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">单例设计模式实现总结</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2021/05/21/devnotes/zhi-mian-java/she-ji-mo-shi/dan-li-she-ji-mo-shi-shi-xian-zong-jie/" title="单例设计模式实现总结"><img class="cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222600.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-05-21</div><div class="title">单例设计模式实现总结</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">dtyy</div><div class="author-info__description">Java全栈</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/dtyytop"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/dtyytop" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:1607961042@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%98%B2%E6%AD%A2%E5%8F%8D%E5%B0%84%E6%94%BB%E5%87%BB"><span class="toc-number">1.</span> <span class="toc-text">防止反射攻击</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%8F%8D%E5%B0%84%E6%94%BB%E5%87%BB%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F"><span class="toc-number">1.1.</span> <span class="toc-text">使用反射攻击单例模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%94%B9%E8%BF%9B%E6%8E%AA%E6%96%BD%EF%BC%9A%E5%8F%8D%E5%B0%84%E9%98%B2%E5%BE%A1"><span class="toc-number">1.2.</span> <span class="toc-text">改进措施：反射防御</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%98%B2%E6%AD%A2%E5%BA%8F%E5%88%97%E5%8C%96%E7%A0%B4%E5%9D%8F%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F"><span class="toc-number">2.</span> <span class="toc-text">防止序列化破坏单例模式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96%E9%97%AE%E9%A2%98"><span class="toc-number">2.1.</span> <span class="toc-text">反序列化问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%94%B9%E8%BF%9B%E6%8E%AA%E6%96%BD%EF%BC%9A%E6%B7%BB%E5%8A%A0readResolve-%E6%96%B9%E6%B3%95"><span class="toc-number">2.2.</span> <span class="toc-text">改进措施：添加readResolve()方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E6%98%AFreadResolve-%EF%BC%8C%E8%80%8C%E4%B8%8D%E6%98%AF%E5%85%B6%E4%BB%96%E6%96%B9%E6%B3%95%EF%BC%9F"><span class="toc-number">2.3.</span> <span class="toc-text">为什么是readResolve()，而不是其他方法？</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222600.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx进程模型"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型">Nginx进程模型</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx核心配置结构"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构">Nginx核心配置结构</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="集群、代理与Nginx"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx">集群、代理与Nginx</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222646.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis主从复制架构与原理"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理">Redis主从复制架构与原理</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222634.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis的两种持久化机制"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制">Redis的两种持久化机制</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By dtyy</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="false"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>